package com.yc.util;

import com.yc.entity.Cartoon;
import com.yc.entity.Pmap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 爬虫工具类
 */
public class SpiderHelper {
    /**
     * 关闭爬取播放地址时在控制台的js输出
     */
//    static {
//        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
//        List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
//        loggerList.forEach(logger -> {
//            logger.setLevel(Level.OFF);
//        });
//    }

    /**
     * 从动漫详情页获取动漫资源基本数据并存到实体类对象中
     * @param addr 动漫详情页地址
     * @return cartoon实体类对象，其中的图片地址为分类
     * @throws IOException
     */
    public static Cartoon getCartoon(String addr) throws IOException {
        URL url = new URL(addr);
        Cartoon cartoon = new Cartoon();
        Document doc = Jsoup.parse(url, 10000);
        String str = "#conch-content>div>div>.container>div>div>div>.hl-dc-content";
        Elements es = doc.select(str).select("div:nth-child(2)").select("ul");
        es = es.select("li");
        for ( int i = 0; i < 12; i++ ) {
            String key = es.get(i).select("em").text();
            key = key.substring(0, key.length() - 1);
            String value = es.get(i).text();
            value = value.substring(3, value.length());
            if ( "片名".equals(key) ) {
                cartoon.setCname(value);
            } else if ( "状态".equals(key) ) {
                cartoon.setCstate(value);
            } else if ( "主演".equals(key) ) {
                cartoon.setProtagonist(value.substring(0, value.length() - 1).replaceAll(" ", ""));
            } else if ( "导演".equals(key) ) {
                cartoon.setDirector(value.substring(0, value.length() - 1).replaceAll(" ", ""));
            } else if ( "年份".equals(key) ) {
                cartoon.setShowYear(value);
            } else if ( "地区".equals(key) ) {
                cartoon.setShowArea(value);
            } else if ( "类型".equals(key) ) {
                cartoon.setCtype(value.substring(0, value.length() - 1).replaceAll(" ", ""));
            } else if ( "时长".equals(key) ) {
                cartoon.setChour(Integer.parseInt(value));
            } else if ( "上映".equals(key) ) {
                cartoon.setShowTime(value.substring(0, value.length() - 4));
            } else if ( "语言".equals(key) ) {
                cartoon.setClanguage(value);
            } else if ( "更新".equals(key) ) {
                cartoon.setLastDate(value);
            } else if ( "简介".equals(key) ) {
                cartoon.setSynopsis(value);
            }
        }
        String ms = doc.select(str).select(".hl-dc-headwrap>div").text();
        cartoon.setAlias(ms == null ? "" : ms);
        String score = doc.select("#conch-content > div.conch-ctwrap-auto > div > div.container > div > div.hl-col-xs-12.hl-col-md-30w.hl-col-lg-3 > div > div.hl-score-wrap.hl-half-items.clearfix > div.hl-bg-site.hl-half-alert.hl-half-y100 > div.hl-score-info.clearfix").select("div.hl-score-nums.hl-text-subs").text();
        cartoon.setCscore(Float.parseFloat(score));
        String num = doc.select("#conch-content > div.conch-ctwrap-auto > div > div.container > div > div.hl-col-xs-12.hl-col-md-30w.hl-col-lg-3 > div > div.hl-score-wrap.hl-half-items.clearfix > div.hl-bg-site.hl-half-alert.hl-half-y100 > div.hl-score-info.clearfix > span").text().replaceAll("次评分", "");
        cartoon.setCommentnum(Integer.parseInt(num));
        String type = doc.select("#conch-content > div.conch-ctwrap.hl-pa0 > div > div > div.hl-crumbs-all.hl-hidden-xs > div > a:nth-child(3)").text();
        cartoon.setCimage(type);
        return cartoon;
    }

    /**
     * 从最近更新页面获取最新数据并根据页面地址进行动漫资源的获取
     *
     * @throws IOException
     */
    public static Map< String, Object > getMap() throws IOException {
        String addr = "https://www.scdmfun.cn/map.html";
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 10000);
        String str = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(1) > a").text();
//        System.out.println(str);
        Elements elements = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li");
        List< Cartoon > cartoonList = new ArrayList<>();
        List< String > stringList = new ArrayList<>();
        Map< String, List<Pmap>> stringListMap = new HashMap<>();
        elements.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
            System.out.println(element.select("li>a").attr("href"));
            String type = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(" + (index + 1) + ") > a > div.hl-item-div.hl-item-div2.hl-col-xs-20w.hl-col-sm-15w.hl-col-md-10w > div").text();
            System.out.println(type);
            if ( "涩涩".equals(type) || "哒咩涩涩".equals(type) ) {
                System.out.println("获取失败");
            } else {
                String add = element.select("li>a").attr("href");
                try {
                    Cartoon cartoon = getCartoon("https://www.scdmfun.cn" + add);
                    cartoonList.add(cartoon);
                    stringListMap.put(cartoon.getCname(), getPlayAdress("https://www.scdmfun.cn" + add));
                } catch ( Exception e ) {
//                    e.printStackTrace();
                    System.out.println("获取失败：" + e.getMessage());
                    stringList.add(add);
                }
            }
        }));
        Map< String, Object > map = new HashMap();
        map.put("cartoonList", cartoonList);
        map.put("stringList", stringList);
        map.put("stringListMap", stringListMap);
        System.out.println(stringList.toString());
        return map;
    }

    /**
     * 获取播放路线和播放页面地址
     *
     * @param
     * @throws IOException
     */
    public static List< List< String > > getPlay(String addr) throws IOException {
        //43.132.171.186
//        String addr = "https://www.scdmfun.cn/bangumi/sc31.html";
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 10000);
        String str = "#hl-plays-list";
        List< List< String > > listList = new ArrayList<>();
        Elements es = doc.select(str);
        es.forEach(element -> {
            List< String > addrlist = new ArrayList<>();
            element.select("li").forEach(element1 -> {
                //System.out.println(element1.text() + ":" + element1.select("a").attr("href"));
                addrlist.add(element1.text());
            });
            listList.add(addrlist);
//            System.out.println("=========分隔线===========");
        });
//        System.out.println(listList.toString());
        return listList;
    }

    public static List< List< Map< String, String > > > getPlay(Document doc) throws IOException {
        String str = "#hl-plays-list";
        List< List< Map< String, String > > > listList = new ArrayList<>();
        Elements es = doc.select(str);
        es.forEach(element -> {
            List< Map< String, String > > addrlist = new ArrayList<>();
            element.select("li").forEach(element1 -> {
                Map map = new HashMap();
                String play = doc.select("#playleft > iframe").attr("src");
                map.put(element1.text(), play);
                addrlist.add(map);
            });
            listList.add(addrlist);
        });
        return listList;
    }

    /**
     * 获取播放路线和播放页面地址
     * @param addr
     * @return
     * @throws IOException
     */
    public static List< List< Map< String, String > > > getPlays(String addr) throws IOException {
//        String addr = "https://www.scdmfun.cn/bangumi/sc31.html";
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 10000);
        String str = "#hl-plays-list";
        Elements es = doc.select(str);
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.setTimeout(5000);
        httpUtils.setWaitForBackgroundJavaScript(5000);
        es.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
            element.select("li").forEach(element1 -> {
                try {
                    Document document = httpUtils.getHtmlPageResponseAsDocument("https://www.scdmfun.cn" +  element1.select("a").attr("href"));
                    //将爬取的数据存进实体类对象
                    String pname = "";
                    if ( index == 0 ) {
                        pname = "双辞动漫①";
                    } else if ( index == 1 ) {
                        pname = "双辞动漫②";
                    }
                    final String fin = pname;
//                    Pmap pmap = new Pmap();
//                    pmap.setPname(fin);
//                    pmap.setCpname(key);
//                    pmap.setPlayaddress(document.select("#playleft > iframe").attr("src"));
//                    pmapLists.add(pmap);
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
            });
        }));
        return null;
    }

    /**
     * 在播放页面进行视频播放源地址的抓取
     * 返回值为pmap实体类对象的集合
     * @param addr  播放页面的地址
     * @param ctid  动漫资源id
     * @return
     * @throws IOException
     */
    public static List<Pmap> getPlayAdress(String addr,Integer ctid) throws IOException {
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 10000);
        String str = "#hl-plays-list";
        Elements es = doc.select(str);
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.setTimeout(3000);
        httpUtils.setWaitForBackgroundJavaScript(3000);
        List< Pmap > pmapList = new ArrayList<>();
        es.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
            element.select("li").forEach(LambdaUtils.consumerWithIndex((element1, index1) -> {
                try {
                    Document document = httpUtils.getHtmlPageResponseAsDocument("https://www.scdmfun.cn" + element.select("li:nth-child(" + (index1 + 1) + ") > a").attr("href"));
                    //将爬取的数据存进实体类对象
                    String pname = "";
                    if ( index == 0 ) {
                        pname = "双辞动漫①";
                    } else if ( index == 1 ) {
                        pname = "双辞动漫②";
                    }
                    Pmap pmap = new Pmap();
                    pmap.setPname(pname);
                    pmap.setCtid(ctid);
                    pmap.setCpname(element.select("#hl-plays-list > li:nth-child(" + (index1 + 1) + ") > a").text());
                    pmap.setPlayaddress(document.select("#playleft > iframe").attr("src"));
                    System.out.println(pmap);
                    pmapList.add(pmap);
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
            }));
        }));
        return pmapList;
    }

    public static List< Pmap > getPlayAdress(String addr) throws IOException {
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.setTimeout(3000);
        httpUtils.setWaitForBackgroundJavaScript(3000);
        //获取该页面下的所有播放页面的地址
        List< List< Map< String, String > > > listList = getPlays(addr);
        List< Pmap > pmapLists = new ArrayList();
        listList.forEach(LambdaUtils.consumerWithIndex((list, index) -> {
            list.forEach(list1 -> {
                list1.forEach((key, value) -> {
                    try {
                        Document document = httpUtils.getHtmlPageResponseAsDocument("https://www.scdmfun.cn" + value);
                        final Integer ctids = 45;
                        //将爬取的数据存进实体类对象
                        String pname = "";
                        if ( index == 0 ) {
                            pname = "双辞动漫①";
                        } else if ( index == 1 ) {
                            pname = "双辞动漫②";
                        }
                        final String fin = pname;
                        Pmap pmap = new Pmap();
                        pmap.setPname(fin);
                        pmap.setCtid(ctids);
                        pmap.setCpname(key);
                        pmap.setPlayaddress(document.select("#playleft > iframe").attr("src"));
                        pmapLists.add(pmap);
                    } catch ( Exception e ) {
                        e.printStackTrace();
                    }
                });
            });
        }));
        pmapLists.forEach(pmap -> {
            System.out.println(pmap);
        });
        return pmapLists;
    }

    public static void main(String[] args) throws IOException {
//        Map map = getMap();
//        List list = (ArrayList) (map.get("stringList"));
//        Map listMap = (HashMap) map.get("stringListMap");
//        list = (ArrayList) (map.get("cartoonList"));
//        ObjectMapper objectMapper = new ObjectMapper();
//        Map pmapMap=new HashMap();
//        for ( int i = 0; i < list.size(); i++ ) {
//            Cartoon cartoon = objectMapper.convertValue(list.get(i), Cartoon.class);
//            List list1 = (ArrayList) listMap.get(cartoon.getCname());
//            List pslist=new ArrayList();
//            list1.forEach(LambdaUtils.consumerWithIndex((list2, index) -> {
//                List pmapList = new ArrayList();
//                List list3 = (ArrayList) list2;
//                String pname = "";
//                if ( index == 0 ) {
//                    pname = "双辞动漫①";
//                } else {
//                    pname = "双辞动漫②";
//                }
//                final String fin=pname;
//                list3.forEach(list4 -> {
//                    Pmap pmap = new Pmap();
//                    pmap.setPname(fin);
//                    pmap.setCtid(cartoon.getCtid());
//                    pmap.setCpname(list4.toString());
//                    pmapList.add(pmap);
//                });
//                pslist.add(pmapList);
//            }));
//            pmapMap.put(cartoon.getCname(),pslist);
////            System.out.println(cartoon);
////            System.out.println(cartoon.getCimage().equals("")?"为空":cartoon.getCimage());
//        }
//        System.out.println(pmapMap.get("Love Live! 虹咲学园校园偶像同好会 第二季"));
        String addr = "https://www.scdmfun.cn/bangumi/sc31.html";
        getPlayAdress(addr);
    }
}
